// pages/user/login.js
const App = getApp()
import Util from '../../utils/util'

Page({

  data: {
    init: false, // 界面是否初始化中
    back: true,
    loading: false, // 是否loading状态

    agree: false,

    mlogin: false,

    mob: '',
    vinfo: '',
    vcode: '',

    butText: '获取验证码',
    butDisabled: false,

    interval: undefined,
    sec: 0,

    next: '',
    refer: {},
  },
  // 页面加载完成
  onLoad(options) {
    this.setData({
      next: options.next || '',
      back: options.back != 'false',
      refer: JSON.parse(options.refer || '{}')
    })
    this.waitForReady()
  },
  onUnload() {
    if (this.data.interval != undefined) {
      clearInterval(this.data.interval)
    }
  },
  waitForReady() {
    if (App.Global.OpenId) {
      this.setData({
        init: true
      })
    } else {
      setTimeout(() => {
        this.waitForReady()
      }, 200);
    }
  },

  execGetVcode() {
    if (this.data.mob.length != 11) {
      return
    }
    if (this.data.butDisabled) {
      return
    }
    this.setData({
      loading: true,
      butDisabled: true
    })
    App.doPost({
      uri: '/app/base/tool/sms/captcha',
      body: {
        mob: this.data.mob
      },
      fnSucc: resp => {
        this.setData({
          sec: resp.data.limit,
          vinfo: resp.data.vinfo,
        })
        let int = setInterval(() => {
          if (this.data.sec <= 1) {
            clearInterval(this.data.interval)
            this.setData({
              sec: 0,
              butText: '验证码',
              butDisabled: false,
              interval: undefined
            })
            return
          }
          this.data.sec = this.data.sec - 1
          this.setData({
            sec: this.data.sec,
            butText: `${this.data.sec} 秒`
          })
        }, 1000);
        this.setData({
          interval: int
        })
        if (App.Global.Debug && resp.data.vcode) {
          wx.showToast({
            icon: 'none',
            title: '测试账号，验证码已自动填写'
          })
          this.setData({
            vcode: resp.data.vcode
          })
        } else {
          wx.showToast({
            title: '验证码已发送'
          })
        }

      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
        this.setData({
          butDisabled: false,
        })
      },
      fnComp: () => {
        this.setData({
          loading: false,
        })
      }
    })
  },
  doMobileLogin() {
    if (!this.data.agree) {
      Util.Toast.fail('请先阅读并同意用户协议和隐私政策')
      return
    }
    if (!this.data.mob) {
      Util.Notify.warn(`请填写手机号`)
      return
    }
    if (!this.data.vinfo) {
      Util.Notify.warn(`请获取验证码`)
      return
    }
    if (!this.data.vcode) {
      Util.Notify.warn(`请填写验证码`)
      return
    }
    this.setData({
      loading: true
    })
    App.doPost({
      uri: '/app/user/account/wxmn/bind',
      body: {
        appid: App.Global.AppId,
        openid: App.Global.OpenId,
        mob: this.data.mob,
        vinfo: this.data.vinfo,
        vcode: this.data.vcode,
        rmch: this.data.refer.mch || '',
        rclk: this.data.refer.clk || '',
      },
      fnSucc: (resp) => {
        if (resp.data.clerk) {
          // 店员登录， 跳转到商家端
          wx.showModal({
            title: "温馨提示",
            showCancel: false,
            content: "请使用商家端小程序操作",
            confirmText: '知道了',
            success: () => {
              wx.navigateToMiniProgram({
                appId: 'wx97f63367fed18eef',
                envVersion: 'release',
                success: () => {
                  wx.exitMiniProgram()
                }
              })
            }

          })
          return
        }

        let user = resp.data.user
        wx.setStorageSync('App.Uid', user.id)
        wx.setStorageSync('App.Token', user.token)
        wx.setStorageSync('App.Name', user.name)
        wx.setStorageSync('App.User', JSON.stringify(user))
        App.Global.User = user
        App.Global.Token = user.token
        wx.pub("ReloadUserInfo", {})
        wx.pub("ReloadUserFin", {})
        Util.Toast.succ('登录成功')

        setTimeout(() => {
          if (this.data.next == 'back') {
            this.getOpenerEventChannel().emit('login', {})
            wx.navigateBack({
              delta: 1,
            })
          } else if (this.data.next != '') {
            wx.redirectTo({
              url: `${decodeURIComponent(this.data.next)}`,
            })
          } else {
            wx.redirectTo({
              url: `/pages/index/index`,
            })
          }
        }, 800)


      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
      },
      fnComp: () => {
        this.setData({
          loading: false,
        })
      }
    })
  },
  onPhoneNumber(e) {
    if (!e.detail.code) {
      return
    }
    if (!this.data.agree) {
      Util.Toast.fail('请先阅读并同意用户协议和隐私政策')
      return
    }
    this.setData({
      loading: true
    })
    App.doPost({
      uri: '/app/user/account/wxmn/register',
      body: {
        appid: App.Global.AppId,
        openid: App.Global.OpenId,
        code: e.detail.code,
        rmch: this.data.refer.mch || '',
        rclk: this.data.refer.clk || '',
      },
      fnSucc: (resp) => {
        if (resp.data.clerk) {
          // 店员登录， 跳转到商家端
          wx.showModal({
            title: "温馨提示",
            showCancel: false,
            content: "请使用商家端小程序操作",
            confirmText: '知道了',
            success: () => {
              wx.navigateToMiniProgram({
                appId: 'wx97f63367fed18eef',
                envVersion: 'release',
                success: () => {
                  wx.exitMiniProgram()
                }
              })
            }
          })
          return
        }

        let user = resp.data.user
        wx.setStorageSync('App.Uid', user.id)
        wx.setStorageSync('App.Token', user.token)
        wx.setStorageSync('App.Name', user.name)
        wx.setStorageSync('App.User', JSON.stringify(user))
        App.Global.User = user
        App.Global.Token = user.token
        wx.pub("ReloadUserInfo", {})
        wx.pub("ReloadUserFin", {})
        Util.Toast.succ('登录成功')
        setTimeout(() => {
          if (this.data.next == 'back') {
            this.getOpenerEventChannel().emit('login', {})

            wx.navigateBack({
              delta: 1,
            })
          } else if (this.data.next != '') {
            wx.redirectTo({
              url: `${decodeURIComponent(this.data.next)}`,
            })
          } else {
            wx.redirectTo({
              url: `/pages/index/index`,
            })
          }
        }, 800)

      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
      },
      fnComp: () => {
        this.setData({
          loading: false,
        })
      }
    })
  },

  doShowMobile() {
    this.setData({
      mlogin: true
    })
  },

  noAgree() {
    if (!this.data.agree) {
      Util.Toast.fail('请先阅读并同意用户协议和隐私政策')
    }
  },
  doAgree() {
    this.setData({
      agree: !this.data.agree
    })
  },
  toAgreement() {
    App.doPost({
      uri: '/app/base/data/config',
      body: {},
      fnSucc: resp => {
        wx.navigateTo({
          url: `/pages/funcs/web?url=${resp.data.web.yhxy}`,
        })
      }
    })
  },

  toPolicy() {
    App.doPost({
      uri: '/app/base/data/config',
      body: {},
      fnSucc: resp => {
        wx.navigateTo({
          url: `/pages/funcs/web?url=${resp.data.web.yszc}`,
        })
      }
    })
  },
})